<!-- 存放大地点 -->
<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="存放大地点">
              <a-select popup-container="html" class="bacClass" v-model="objectOP.bigClassName1"
                        :filter-option="false" allow-search allow-clear @focus="WLfocusSel('')"
                        @search="WLfocusSel($event)" style="width:150px">
                <a-option v-for="item in objectOP.bigName1" :value="item.depositBigLocation">
                  {{ item.depositBigLocation }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar :items="pageData.btnList" @add="addHandler" @del="deleteHandler" @select="selectHandler">
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18"/>
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
        </a-divider>
      </div>
      <div class="my-tool-bar">
      </div>
    </template>
    <template #pageTabel>
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:100%;width: 100%;z-index:999 ;">
        <div style="width: 100%; height: 100%">
          <encapsulation-agrid ref="table1Ref" :configaggrid="configTable1"></encapsulation-agrid>
        </div>
      </a-spin>
    </template>
    <a-drawer style="z-index:999" ok-text='保存' cancel-text='关闭' :mask-closable="false"
              :drawer-style="{ 'zIndex': 9999 }" :width="400" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
              @cancel="pageData.showAdd = false" :ok-loading="pageData.pageLoading">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item label="编号" field="code" label-col-flex="80px"
                       :rules="[{ required: true, message: '编号必填' }]" :validate-trigger="['change', 'blur']">
            <a-input class="bacClass" placeholder="" v-model="dataForm.code" @blur="inputBlur"/>
          </a-form-item>
          <a-form-item label="存放大地点" field="depositBigLocation"
                       :rules="[{ required: true, message: '存放大地点必填' }]"
                       label-col-flex="80px" :validate-trigger="['change', 'blur']">
            <a-input class="bacClass" placeholder="" v-model="dataForm.depositBigLocation"/>
          </a-form-item>
          <a-form-item label="备注" field="remark" label-col-flex="80px">
            <a-textarea class="bacClass" v-model="dataForm.remark" :max-length="400" allow-clear
                        show-word-limit/>
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script setup lang="ts">

import {post} from '@/api/http'
import {usePagination, useRowKey, useRowSelection, useTable, useTableColumn} from '@/hooks/table';
import emitter from "@/hooks/useEventBus";
import {onMounted, reactive, ref} from 'vue'
import {Message, Modal} from '@arco-design/web-vue';
import {FormInstance} from '@arco-design/web-vue/es/form';
import usePermission from '@/store/modules/permission'

import {localeText} from '@/api/aggridZw'
import {pagingList} from '@/api/paging'
import {simplifyMessages} from '@/api/messageSimplification'
import {saveOrUpdateGridState as saveOrUpdateGridState01} from '@/hooks/useGridState'
import buttionRender from "@/components/aggridCellRenDerer/buttionRender.vue";

interface ProcurementType {
  "id": any
  "code": any
  "depositBigLocation": any
  "remark": any
}

const pageData = reactive<{
  nameList: [],
  showAdd: boolean,
  sideTitle: string,
  dropDownData: any,
  pageLoading: boolean,
  rHeight: any
  btnList: any[],
  isEdit: boolean
}>({
  nameList: [],
  showAdd: false,
  sideTitle: '新增存放大地点',
  dropDownData: "",
  pageLoading: false,
  rHeight: "",
  btnList: [],
  isEdit: false
});
//设置权限
// ['查询', '新增', '删除', '导出', '导入']
const permissionStore = usePermission()

if (permissionStore.hasPermisson('cfddd.cx')) {

  pageData.btnList.push("查询")
}
if (permissionStore.hasPermisson('cfddd.xz')) {
  pageData.btnList.push("新增")
}
if (permissionStore.hasPermisson('cfddd.sc')) {
  pageData.btnList.push("删除")
}
// pageData.btnList.push("导入")
if (permissionStore.hasPermisson('cfddd.xg')) {
  pageData.isEdit = true
}
const objectOP = reactive<any>({
  bigClassName1: '',
  bigName1: [],
})
const table1Ref = ref<any>(null)
const tableColumns = [
  {
    field: '',
    headerCheckboxSelection: true,
    checkboxSelection: true,
    width: 50,
    showDisabledCheckboxes: false,
    pinned: 'left',
  },
  {
    headerName: "物料编号",
    field: "code",
    width: 150
  },
  {
    headerName: "存放大地点",
    field: "depositBigLocation",
    width: 150
  },
  {
    headerName: "备注",
    field: "remark",
    width: 150
  },
  {
    headerName: "创建人",
    field: "createName",
    width: 150
  },
  {
    headerName: "创建时间",
    field: "createTime",
    width: 200
  },
  {
    headerName: "最后修改人",
    field: "updateName",
    width: 150
  },
  {
    headerName: "最后修改时间",
    field: "updateTime",
    width: 200
  },
  {
    headerName: '操作',
    field: 'action',
    slotName: 'action',
    width: 150,
    pinned: 'right',
    cellRenderer: buttionRender,
    cellRendererParams: {
      buttonList: [
        {
          type: 'primary',
          text: '修改',
          show: pageData.isEdit,
          typeName: 'el-button',
          Callback: (data: any) => {
            editHandler(data)
          },
        },
      ],
      eltagSize: 0,
    },
  }
]
let configTable1 = {
  url: 'purchase/DepositBigLocation/getPage', //接口路径
  queryData: {
    deleteState: 0,
    depositBigLocation: objectOP.bigClassName1
  },
  paginationShow: true, //分页是否显示
  invokeiIterface: true, //是否调用接
  rowMultiSelectWithClick: true, //点击行是否多选
  column: tableColumns,
  fileName: 'StoreInLargeLocations01',
}
const total = ref(0);
const page = ref(1);
const size = ref(10);

function PageSize(val: any) {
  pagination.page = val
  doRefresh();
}

function change1(val: any) {
  pagination.pageSize = val
  doRefresh();
}

function doRefresh() {
  table1Ref.value.setQuery({
    deleteState: 0,
    depositBigLocation: objectOP.bigClassName1
  })
}

const {selectedRowKeys, onSelectionChange} = useRowSelection();
const pagination = usePagination(doRefresh);
const table = useTable();
const rowKey = useRowKey("id");
onMounted(() => {
  doRefresh();
  // 切换tap到本页面执行的方法
  emitter.on("StoreInLargeLocations", () => {
    doRefresh();
  });

  pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight
  //表格的高
  if (pageData.rHeight !== undefined) {
    pageData.rHeight = pageData.rHeight - 200;

    console.log(pageData.rHeight);

  }
  window.addEventListener('resize', () => {
    pageData.rHeight = document.getElementById("BaseInfoSetting")?.clientHeight

    //表格的高
    if (pageData.rHeight !== undefined) {
      pageData.rHeight = pageData.rHeight - 200;
    }

  })
});
//查询
const selectHandler = () => {
  pagination.page = 1
  doRefresh();
}
const addHandler = () => {
  //清空数据
  for (const key in dataForm) {
    if (key == "id") {
      dataForm.id = null;
    } else {
      dataForm[key] = '';
    }
  }
  pageData.showAdd = true
  pageData.sideTitle = '新增存放大地点'

}

const dataForm = reactive<ProcurementType>({
  "id": null,
  "code": '',
  "depositBigLocation": '',
  "remark": ''
})

// 表格准备事件
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
  colState.value = params.columnApi
}

const formRef = ref<FormInstance>()
const sideOk = () => {
  formRef.value?.validate().then((err) => {
    if (!err) {
      if (pageData.sideTitle === "新增存放大地点") {
        dataForm.id = null
        pageData.pageLoading = true
        post({
          url: "/purchase/DepositBigLocation/insert",
          data: [dataForm],
        }).then((res: any) => {
          if (res.code === 200) {
            formRef.value?.resetFields();
            pageData.showAdd = false;
            doRefresh();
            Message.success({
              content: "新增成功",
              duration: 5000,
            });
          } else {
            Message.error({
              content: res.message,
              duration: 5000,
            });
          }
        }).finally(() => {
          pageData.pageLoading = false
        })
      } else {
        post({
          url: "/purchase/DepositBigLocation/update",
          data: [dataForm],
        }).then((res: any) => {
          if (res.code === 200) {
            formRef.value?.resetFields();
            pageData.showAdd = false;
            doRefresh();
            //清空数据
            for (const key in dataForm) {
              if (key == "id") {
                dataForm.id = null;
              } else {
                dataForm[key] = '';
              }
            }
            Message.success({
              content: "修改成功",
              duration: 5000,
            });
          } else {
            Message.error({
              content: simplifyMessages(res.message),
              duration: 5000,
            });
          }
        });
      }
    }
  });
}
const deleteHandler = () => {
  if (table1Ref.value.getSelectedRows().length === 0) {
    Message.error('请先勾选');
    return
  }
  Modal.confirm({
    title: '系统提示',
    content: '确认删除选中的数据?',
    onOk() {
      post({
        url: '/purchase/DepositBigLocation/delete',
        data: table1Ref.value.getSelectedRows().map((o: any) => {
          return o.id
        })
      }).then(({code, data, message}: any) => {
        if (code === 200) {
          Message.success({
            content: '删除成功',
            duration: 5000
          })
          page.value = 1
          doRefresh()
        } else {
          Message.error({
            content: simplifyMessages(message),
            duration: 5000
          })
        }
      })
    }
  })
}
const editHandler = (record: ProcurementType) => {
  dataForm.id = Number(record.id);
  dataForm.code = record.code;
  dataForm.depositBigLocation = record.depositBigLocation;
  dataForm.remark = record.remark;
  pageData.sideTitle = '修改存放大地点'
  pageData.showAdd = true
};

//input离开焦点 将小写转大写
const inputBlur = () => {
  dataForm.code = dataForm.code.toUpperCase();
}
const headerShow = ref<boolean>(true)
const defaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
  // flex: 1
}
const huiche = () => {
  selectHandler();
}
const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)
const isChiese = (value: string, cb: Function) => {
  return new Promise<void>((resolve) => {
    var reg = /^[\u4E00-\u9FA5]+$/;
    if (!reg.test(value)) {
      cb('请填写中文！')
    }
    resolve()
  })
}
//下拉框   存放大地点  
const WLfocusSel = (val: any) => {
  post({
    url: '/purchase/DepositBigLocation/getFieldValue',
    data: {depositBigLocation: val},
  }).then(({data, code}: any) => {
    if (code === 200) {
      objectOP.bigName1 = data
    } else {
      Message.error({
        content: '查询失败！',
        duration: 5000,
      })
    }
  })
}
</script>

<style lang="less"></style>